package com.wakala.employment.fragment.member;

import android.annotation.SuppressLint;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.viewpager2.widget.MarginPageTransformer;

import com.android.tu.loadingdialog.LoadingDailog;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.kongzue.dialogx.dialogs.BottomDialog;
import com.kongzue.dialogx.dialogs.CustomDialog;
import com.kongzue.dialogx.interfaces.BottomDialogSlideEventLifecycleCallback;
import com.kongzue.dialogx.interfaces.OnBindView;
import com.leaf.library.StatusBarUtil;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.CenterPopupView;
import com.stx.xhb.androidx.XBanner;
import com.tencent.mm.opensdk.constants.Build;
import com.tencent.mm.opensdk.modelbiz.WXLaunchMiniProgram;
import com.tencent.mm.opensdk.modelbiz.WXOpenCustomerServiceChat;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.wakala.employment.MyApp;
import com.wakala.employment.R;
import com.wakala.employment.adapter.banner.CustomViewsInfo;
import com.wakala.employment.adapter.banner.MultiplePageTransformer;
import com.wakala.employment.adapter.bean.ImageBannerBean;
import com.wakala.employment.adapter.entity.User;
import com.wakala.employment.core.BaseFragment;
import com.wakala.employment.core.constants.UserRoleEnum;
import com.wakala.employment.core.http.subscriber.NoTipRequestSubscriber;
import com.wakala.employment.databinding.FragmentMemberBinding;
import com.wakala.employment.fragment.news.InformationFragment;
import com.wakala.employment.fragment.other.BlankFragment;
import com.wakala.employment.fragment.other.CommunicateRecordFragment;
import com.wakala.employment.fragment.other.CompanyCertificationFragment;
import com.wakala.employment.fragment.other.FeedBackFragment;
import com.wakala.employment.fragment.other.MemberVipFragment;
import com.wakala.employment.fragment.other.PrivacyPolicyFragment;
import com.wakala.employment.fragment.other.RealNameAuthFragment;
import com.wakala.employment.fragment.other.ResumeExigenceFragment;
import com.wakala.employment.fragment.other.SettingsFragment;
import com.wakala.employment.fragment.other.UserCouponFragment;
import com.wakala.employment.fragment.other.UserGetIntegralFragment;
import com.wakala.employment.fragment.other.UserIntegralFragment;
import com.wakala.employment.fragment.other.UserTaskCenterFragment;
import com.wakala.employment.fragment.other.VisitRecordFragment;
import com.wakala.employment.fragment.profile.CollectionJobListFragment;
import com.wakala.employment.fragment.profile.ProfileFragment;
import com.wakala.employment.fragment.profile.ResumeFragment;
import com.wakala.employment.fragment.recruit.RecruitManageFragment;
import com.wakala.employment.fragment.recruit.ResumeRefreshFragment;
import com.wakala.employment.http.TestApi;
import com.wakala.employment.http.manager.TokenManager;
import com.wakala.employment.utils.TokenUtils;
import com.wakala.employment.utils.Utils;
import com.xuexiang.xhttp2.XHttpProxy;
import com.xuexiang.xhttp2.exception.ApiException;
import com.xuexiang.xpage.annotation.Page;
import com.xuexiang.xpage.enums.CoreAnim;
import com.xuexiang.xui.widget.actionbar.TitleBar;
import com.xuexiang.xutil.app.AppUtils;
import com.xuexiang.xutil.tip.ToastUtils;
import com.youth.banner.adapter.BannerImageAdapter;
import com.youth.banner.holder.BannerImageHolder;
import com.youth.banner.transformer.ScaleInTransformer;
import com.youth.banner.transformer.ZoomOutPageTransformer;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * A simple {@link Fragment} subclass.
 * create an instance of this fragment.
 */
@Page(anim = CoreAnim.none)
public class MemberFragment extends BaseFragment<FragmentMemberBinding> implements View.OnClickListener {

    private boolean  hasAdShowed = false;

    LoadingDailog dialog;
    @NonNull
    @Override
    protected FragmentMemberBinding viewBindingInflate(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, boolean attachToRoot) {
        return FragmentMemberBinding.inflate(inflater, container, attachToRoot);
    }

    @Override
    protected void initViews() {
        // 暂时屏蔽 赚钱专区
        binding.cardView4.setVisibility(View.GONE);
        bindData(null);
        //initBanner();
        initXBanner();
        initLoadingDialog();
    }

    private void initLoadingDialog(){
        LoadingDailog.Builder loadBuilder=new LoadingDailog.Builder(getContext())
                .setMessage("处理中...")
                .setCancelable(true)
                .setCancelOutside(true);
        dialog=loadBuilder.create();
    }

    @Override
    protected void initListeners() {
        binding.tvSetting.setOnClickListener(this);
        binding.ibSetting.setOnClickListener(this);
        //客服
        binding.ivKefu.setOnClickListener(this);
        binding.tvKefu.setOnClickListener(this);
        binding.btnModifyProfile.setOnClickListener(this);
        binding.ssBtnModifyResume.setOnClickListener(this);
        binding.memberImg.setOnClickListener(this);
        //积分
        binding.lvJifen.setOnClickListener(this);
        //沟通过
        binding.lvGoutongjilu.setOnClickListener(this);
        //查看过
        binding.lvChakanjilu.setOnClickListener(this);
        //收藏
        binding.lvCollection.setOnClickListener(this);
        //会员
        binding.ssBtnMemberVip.setOnClickListener(this);
        //在线简历
        binding.menuOnlineResume.setOnClickListener(this);
        //会员套餐
        binding.menuVipPackage.setOnClickListener(this);
        //加急找活
        binding.menuResumeUrgency.setOnClickListener(this);
        //刷新简历
        binding.menuResumeRefresh.setOnClickListener(this);
        //招聘数据
        binding.menuRecruitData.setOnClickListener(this);
        //菜单 设置
        binding.menuSettings.setOnClickListener(this);
        //菜单 - 招聘 -套餐
        binding.menuRecuritPackage.setOnClickListener(this);
        //菜单 - 招聘 -任务
        binding.menuRecruitTask.setOnClickListener(this);
        //菜单 - 赚钱商城
        binding.menuComMall.setOnClickListener(this);
        //菜单-服务-获取积分
        binding.menuServiceJifeng.setOnClickListener(this);
        //菜单-服务-任务中心
        binding.menuServiceTaskCenter.setOnClickListener(this);
        //菜单-服务-实名认证
        binding.menuServiceRealNameAuth.setOnClickListener(this);
        //菜单-服务-企业认证
        binding.menuServiceEnterpriseAuth.setOnClickListener(this);
        //菜单-服务-河狸资讯
        binding.menuServiceInformation.setOnClickListener(this);
        //菜单-服务-我的卡券
        binding.menuServiceCoupon.setOnClickListener(this);
        //菜单-服务-我的关注
        binding.menuServiceGuanzhu.setOnClickListener(this);
        //菜单-服务-用户查询
        binding.menuServiceUserSearch.setOnClickListener(this);
        //菜单-服务-河狸商城
        binding.menuServiceHeliShop.setOnClickListener(this);
        //菜单-帮助-系统设置
        binding.menuSettings.setOnClickListener(this);
        //菜单-帮助-意见反馈
        binding.menuHelpFeedback.setOnClickListener(this);
        //菜单-公司资质
        binding.menuCompanyCertification.setOnClickListener(this);
        //菜单-隐私政策
        binding.menuPrivacyPolicy.setOnClickListener(this);


    }

   /* private void initBanner(){
        List<ImageBannerBean> mImages = new ArrayList<>();
        mImages.add(new ImageBannerBean(R.mipmap.ad_banner01, "相信自己,你努力的样子真的很美", 1));
        mImages.add(new ImageBannerBean(R.mipmap.ad_banner02, "相信自己,你努力的样子真的很美", 2));
        mImages.add(new ImageBannerBean(R.mipmap.ad_banner01, "相信自己,你努力的样子真的很美", 1));
        mImages.add(new ImageBannerBean(R.mipmap.ad_banner02, "相信自己,你努力的样子真的很美", 2));
        binding.banner.setAdapter(new BannerImageAdapter<ImageBannerBean>(mImages) {
            @Override
            public int getItemCount() {
                return mImages.size();
            }

            @Override
            public void onBindView(BannerImageHolder holder, ImageBannerBean data, int position, int size) {
                holder.imageView.setImageResource(data.getImageRes());
            }
        });

        binding.banner.setBannerRound2(10f);
       // binding.banner.addPageTransformer(new MarginPageTransformer(0));
       binding.banner.addPageTransformer(new ScaleInTransformer());
        //--
    }*/

    private void initXBanner(){
        //获取控件
        XBanner mXBanner = (XBanner) findViewById(R.id.xbanner);
        List<CustomViewsInfo> data = new ArrayList<>();
        data.add(new CustomViewsInfo("邀请好友赚积分"));
        data.add(new CustomViewsInfo("专业企业服务"));
        data.add(new CustomViewsInfo("招工找活不发愁"));
        data.add(new CustomViewsInfo("灵活就业轻松自由"));
        mXBanner.setBannerData(R.layout.banner_custome, data);
        mXBanner.loadImage(new XBanner.XBannerAdapter() {
            @Override
            public void loadBanner(XBanner banner, Object model, View view, int position) {
                TextView tvContent = (TextView) view.findViewById(R.id.tv_sub_title);
                tvContent.setText(((CustomViewsInfo) model).getTitle());
                //view.setBackgroundColor(Color.parseColor(((CustomViewsInfo) model).getXBannerUrl()));
            }
        });
        mXBanner.setOnItemClickListener(new XBanner.OnItemClickListener() {
            @Override
            public void onItemClick(XBanner banner, Object model, View view, int position) {
                //ToastUtils.toast("点击了" + position);
            }
        });
    }

    @Override
    protected void startLazyData() {
        super.startLazyData();
        this.initTitle();
        if(!hasAdShowed){
            initAdTip();
            hasAdShowed= true;
        }
        //
        initMemberMenu();

    }
   private void initMemberMenu(){
        if(MyApp.User_Role== UserRoleEnum.BOOS){
            binding.cardView2.setVisibility(View.GONE);
            binding.cardView22.setVisibility(View.VISIBLE);
            binding.cardView3.setVisibility(View.GONE);
        }else{
            binding.cardView2.setVisibility(View.VISIBLE);
            binding.cardView22.setVisibility(View.GONE);
            binding.cardView3.setVisibility(View.VISIBLE);
        }
   }

    private void initAdTip(){
        CustomDialog.build()
                .setCustomView(new OnBindView<CustomDialog>(R.layout.dialog_ad_tips) {
                    @Override
                    public void onBind(final CustomDialog dialog, View v) {
                        ImageView btnOk;
                        btnOk = v.findViewById(R.id.iv_close);
                        btnOk.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                dialog.dismiss();
                            }
                        });
                        ImageView ivTop = v.findViewById(R.id.iv_top);
                        ivTop.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                openNewPage(MemberVipFragment.class);
                                dialog.dismiss();
                            }
                        });
                    }
                }).setMaskColor(getResources().getColor(R.color.black30))
                .show();
    }

    /**
     * @return 返回为 null意为不需要导航栏
     */
    @Override
    protected TitleBar initTitle() {
        //StatusBarUtil.setDarkMode(getActivity());
        //设置状态栏背景颜色，如果设置为 Color.TRANSPARENT 将会隐藏状态栏
        getActivity().getWindow().setStatusBarColor(getResources().getColor(R.color.xui_config_color_light2));
        return null;
    }


    @Override
    public void onClick(View view) {
        int id = view.getId();
        if(id== R.id.tv_setting){
            openNewPage(SettingsFragment.class);
        }else if(id == R.id.ib_setting){
            openNewPage(SettingsFragment.class);
        }else if(id == R.id.tv_kefu){
            openKefu();
        }else if(id == R.id.iv_kefu){
            openKefu();
        } else if (id == R.id.ssBtn_modify_resume) {
            openNewPage(ResumeFragment.class);
        } else if (id == R.id.btn_modify_profile) {
            openNewPage(ProfileFragment.class);
        } else if (id == R.id.member_img) {
            //点击头像刷新会员界面数据
            getLoginUserInfo();
        } else if (id == R.id.ssBtn_member_vip) {
            //会员开通
            openNewPage(MemberVipFragment.class);
        } else if (id == R.id.menu_online_resume) {
            openNewPage(ResumeFragment.class);
        }  else if (id == R.id.menu_vip_package) {
            //会员套餐
            openNewPage(MemberVipFragment.class);
        } else if (id == R.id.menu_resume_urgency) {
            //加急简历
            openNewPage(ResumeExigenceFragment.class);
        } else if (id == R.id.menu_resume_refresh) {
            //刷新简历
            openNewPage(ResumeRefreshFragment.class);
        } else if (id == R.id.menu_recruit_data) {
            openNewPage(RecruitManageFragment.class);
        } else if (id==R.id.lv_jifen) {
            //积分
            openNewPage(UserIntegralFragment.class);
        } else if (id == R.id.lv_goutongjilu) {
            //沟通过
            openNewPage(CommunicateRecordFragment.class);
        } else if (id==R.id.lv_chakanjilu) {
            //查看过
            openNewPage(VisitRecordFragment.class);
        } else if (id ==R.id.lv_collection) {
            //收藏
            openNewPage(CollectionJobListFragment.class);
        }  else if (id == R.id.menu_service_real_name_auth) {
            openNewPage(RealNameAuthFragment.class);
        } else if (id == R.id.menu_service_jifeng) {
            //获取积分
            openNewPage(UserGetIntegralFragment.class);
        } else if (id == R.id.menu_service_task_center) {
            //任务中心
            openNewPage(UserTaskCenterFragment.class);
        } else if (id == R.id.menu_service_enterprise_auth) {
            //企业认证
            showEnterpriseAuthDialog();
        } else if (id ==R.id.menu_service_coupon) {
            //卡券
            openNewPage(UserCouponFragment.class);
        }  else if (id ==R.id.menu_service_information) {
            //河狸资讯
            openNewPage(InformationFragment.class);
        } else if (id ==R.id.menu_service_user_search) {
            //用户查询

        } else if (id ==R.id.menu_service_heli_shop) {
            //河狸商城
            openHlzxWxMinApp();
        } else if (id ==R.id.menu_settings) {
            //系统设置
            openNewPage(SettingsFragment.class);
        } else if (id ==R.id.menu_help_feedback) {
            //意见反馈
            openNewPage(FeedBackFragment.class);
        } else if (id ==R.id.menu_company_certification) {
            //公司认证
            openNewPage(CompanyCertificationFragment.class);
        } else if (id ==R.id.menu_privacy_policy) {
            //隐私政策
            openNewPage(PrivacyPolicyFragment.class);
        } else {
            openNewPage(BlankFragment.class);
        }
    }

    private void openHlzxWxMinApp() {

        String appId = "wxe8a910123413ba65"; // 填移动应用(App)的 AppId，非小程序的 AppID
        IWXAPI api = WXAPIFactory.createWXAPI(requireContext(), appId);

        WXLaunchMiniProgram.Req req = new WXLaunchMiniProgram.Req();
        req.userName = "gh_83ab3010e732"; // 填小程序原始id
        req.path = "";                  //拉起小程序页面的可带参路径，不填默认拉起小程序首页，对于小游戏，可以只传入 query 部分，来实现传参效果，如：传入 "?foo=bar"。
        req.miniprogramType = WXLaunchMiniProgram.Req.MINIPTOGRAM_TYPE_RELEASE;// 可选打开 开发版，体验版和正式版
        api.sendReq(req);

    }

    /**
     * 打开客服
     */
    private void openKefu(){
        String appId = "wxe8a910123413ba65"; // 填移动应用(App)的 AppId
        IWXAPI api = WXAPIFactory.createWXAPI(requireContext(), appId);
        // 判断当前版本是否支持拉起客服会话
        if (api.getWXAppSupportAPI() >= Build.SUPPORT_OPEN_CUSTOMER_SERVICE_CHAT) {
            WXOpenCustomerServiceChat.Req req = new WXOpenCustomerServiceChat.Req();
            req.corpId = "wwa201bef9182dd47e";							      // 企业微信 ID
            req.url = "https://work.weixin.qq.com/kfid/kfc1a000ec98182ebd4";	// 企业微信 客服URL
            api.sendReq(req);
        }else {
            new XPopup.Builder(getContext()).asCustom(new CenterPopupView(requireContext()) {
                @Override
                protected int getImplLayoutId() {
                    return R.layout.dialog_alter;
                }

                @Override
                protected void onCreate() {
                    super.onCreate();
                    findViewById(R.id.btn_confirm).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            dismiss();
                        }
                    });
                    TextView title = findViewById(R.id.txt_dialog_content);
                    title.setText("微信搜索：河狸科技 公众号");
                }
            }).show();
        }
    }

    /**
     * 更新会员信息
     */
    private void updateMemberInfo(){

    }

    private void bindData(User user) {
        if (null == user) {
            if (TokenManager.getInstance().isUserLogined()) {
                user = TokenUtils.getmLoginUser();
            }
        }

        if (null != user) {
            binding.tvUserName.setText(user.getNickname());
            //
            if (Utils.isHttpAddress(user.getAvatar())) {
                RequestOptions options = new RequestOptions()
                        .centerCrop()
                        .placeholder(R.color.color_f4)
                        .diskCacheStrategy(DiskCacheStrategy.ALL);
                Glide.with(binding.memberImg.getContext()).load(user.getAvatar())
                        .apply(options)
                        .into(binding.memberImg);
            }
        }

    }

    /**
     **
     * 根据token获取当前登录用户信息
     */
    @SuppressLint("CheckResult")
    private void getLoginUserInfo(){
        dialog.show();
        XHttpProxy.proxy(TestApi.IUserService.class)
                .getLoginUserInfo()
                .subscribeWith(new NoTipRequestSubscriber<User>() {
                    @Override
                    public void onSuccess(User user) {
                        dialog.dismiss();
                        TokenUtils.clearLoginUser();
                        TokenUtils.setmLoginUser(user);
                        bindData(user);
                    }
                    @Override
                    public void onError(ApiException e) {
                        dialog.dismiss();
                        super.onError(e);
                        ToastUtils.toast(e.getDisplayMessage());
                    }
                });
    }

    private void showEnterpriseAuthDialog(){
        new BottomDialog("提示", "需要先完成个人实名认证才能进行企业认证", new OnBindView<BottomDialog>(R.layout.layout_custom_dialog_view) {
            @SuppressLint("UseCompatLoadingForDrawables")
            @Override
            public void onBind(BottomDialog dialog, View v) {
                if (dialog.getDialogImpl().imgTab != null) {
                    ((ViewGroup) dialog.getDialogImpl().imgTab.getParent()).removeView(dialog.getDialogImpl().imgTab);
                }
                v.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialog.dismiss();
                    }
                });
                v.findViewById(R.id.btn_close).setOnClickListener(v1 -> dialog.dismiss());
                //
               ImageView imageView=  v.findViewById(R.id.img_ico);
               imageView.setImageDrawable(getResources().getDrawable(R.drawable.icon_enterpirce_auth_logo));
               TextView textView = v.findViewById(R.id.tv_text);
               textView.setText("企业认证后将获得企业专属LOGO展示");
            }
        }).setDialogLifecycleCallback(new BottomDialogSlideEventLifecycleCallback<BottomDialog>() {
            @Override
            public boolean onSlideClose(BottomDialog dialog) {
                return super.onSlideClose(dialog);
            }

            @Override
            public boolean onSlideTouchEvent(BottomDialog dialog, View v, MotionEvent event) {

                return super.onSlideTouchEvent(dialog, v, event);
            }
        }).show();
    }

}